<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sq="http://www.w3.org/1999/html">
<head>
  <th:block th:include="include :: header"/>
</head>
<body class="gray-bg">
<div class="wrapper wrapper-content animated fadeInRight">
  <div class="ibox float-e-margins">
    <!--   <div class="ibox-title">
         <h5>数据检索</h5>
       </div>-->
    <div class="ibox-content">
      <form id="searchForm" name="searchForm" role="form" class="sq-searchForm">
        <div class="row">
          <div class="col-sm-3">
            <div class="form-group">
              <input type="text" placeholder="请输入账号" name="username" class="form-control required">
            </div>
          </div>
          <div class="col-sm-3">
            <div class="form-group">
              <input type="text" placeholder="请输入用户名" name="surname" class="form-control">
            </div>
          </div>
          <div class="col-sm-3">
            <div class="form-group">
              <sq:select name="status" dicCode="1001" pleaseChoose="用户状态"></sq:select>
            </div>
          </div>
          <div class="col-sm-3" align="right">
            <button onclick="search()" class="btn btn-primary" type="button">
              <i class="fa fa-search"></i>&nbsp;搜索
            </button>
            <button onclick="reset()" class="btn btn-primary btn-outline" type="button">
              <i class="fa fa-recycle"></i>&nbsp;重置
            </button>
          </div>
        </div>
      </form>
    </div>

    <div class="ibox-content">
      <div class="row row-lg">
        <div class="col-sm-12">
          <div class="example-wrap">
            <div id="toolbar" class="form-group sq-toolbar">
              <button onclick="add()" class="btn btn-primary" type="button">新增</button>
              <button onclick="edit()" class="btn btn-warning" type="button">编辑</button>
              <button onclick="del()" class="btn btn-danger" type="button">删除</button>
              <button onclick="relateRole()" class="btn btn-default" type="button">分配角色</button>
              <button onclick="relateOrg()" class="btn btn-default btn-outline" type="button">分配机构</button>
              <button onclick="unlock()" class="btn btn-success btn-outline" type="button">解锁用户</button>
            </div>
            <div class="example">
              <table id="dataTable"></table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="modal inmodal" id="roleModal" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content animated fadeIn">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">
          <span aria-hidden="true">&times;</span>
          <span class="sr-only">Close</span>
        </button>
        <h4 class="modal-title">分配角色</h4>
      </div>
      <div class="modal-body">
        <div class="ibox-content">
          <form id="roleSearchForm" name="roleSearchForm" role="form" class="form-inline">
            <div class="form-group" style="margin-bottom: 7px;">
              <input type="text" id="roleName" name="roleName" placeholder="请输入角色名" class="form-control">
            </div>
            <button onclick="search($('#roleTable'))" class="btn btn-primary" type="button"
                    style="margin-bottom: 7px;">搜索
            </button>
          </form>
          <input type="hidden" id="ruid" name="ruid">
          <table id="roleTable"></table>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-primary" type="button" onclick="saveRoleData()">提交</button>
        <button type="button" class="btn btn-white" data-dismiss="modal">关闭</button>
      </div>
    </div>
  </div>
</div>

<div class="modal inmodal" id="orgModal" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content animated fadeIn">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">
          <span aria-hidden="true">&times;</span>
          <span class="sr-only">Close</span>
        </button>
        <h4 class="modal-title">
          分配机构
        </h4>
      </div>
      <div class="modal-body">
        <div class="ibox-content">
          <input type="hidden" id="ouid" name="ouid">
          <ul id="tree" class="ztree" style="width:560px; overflow:auto;"></ul>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" onclick="saveTree()">
          提交
        </button>
        <button type="button" class="btn btn-white" data-dismiss="modal">
          关闭
        </button>
      </div>
    </div>
  </div>
</div>
</body>
<th:block th:include="include :: footer"/>
<script th:inline="javascript">
    const requestPath = parent.api.sys.user
    let columns = [
        {
            field: "select",
            checkbox: true, //给多选框赋一个field值为“select”用于更改选择状态
            // width: "5px"
        }, {
            title: "登录账号",//标题
            field: "username",//键名
            width: "25%"
        }, {
            title: "用户名",
            field: "surname",
            width: "30%"
        },/* {
            title: "手机号",
            field: "mobile",
            width: "25%"
        }, */{
            title: "状态",
            field: "status",
            formatter: function (value, row, index) {
                return parent.formartDic(value, '1001')
            },
            width: "15%"
        }, {
            title: "锁定时间",
            field: "lockTime",
       /*     formatter: function (value, row, index) {
                if (row.lockTime) {
                    let dateArr= row.lockTime.split(' ');
                    let dayArr = dateArr[0].split('-');
                    let secondArr = dateArr[1].split(':');
                    if (value >= 5 && new Date().getTime() < new Date(dayArr[0], parseInt(dayArr[1]) - 1, dayArr[2], secondArr[0], secondArr[1], secondArr[2]).getTime()) {
                        return "已锁定"
                    }
                }

                return "未锁定";
            },*/
            width: "15%"
        }, {
        title: "连续密码错误次数",
        field: "errNum",
        }, {
            title: "创建时间",
            field: "createTime",
            width: "30%"
        }
    ]
    $(function () {
        initTable(columns);
    })

    let roleColumns = [
        {
            field: "select",
            checkbox: true //给多选框赋一个field值为“select”用于更改选择状态
        }, {
            title: "角色名称",//标题
            field: "roleName",//键名
        }, {
            title: "备注",
            field: "remark"
        }
    ]

    //分配角色
    function relateRole() {
        if (validCheckOne()) {
            $("#roleName").val('')
            $("#roleTable").bootstrapTable('refresh')
            //判断是否有选中的数据
            $("#ruid").val(getSelectedId($("#dataTable")));//设置弹出层中的用户ID

            $('#roleTable').bootstrapTable({
                url: parent.api.sys.role.query,
                method: "get",//请求方式  POST后台拿不到参数
                dataType: "json",//返回数据类型
                search: false,//是否显示表格搜索，此搜索是客户端搜索，不会进服务端
                showColumns: false,//列选择按钮
                showRefresh: false,//刷新按钮
                showExport: false,
                pagination: true,//是否显示分页（*）
                striped: true,//是否显示行间隔色
                cache: false,//是否使用缓存，默认为true
                queryParams: function (params) {
                    let formObj = formToObj($("#roleSearchForm"))
                    return Object.assign(formObj, {
                        userId: $("#ruid").val(),
                        size: params.limit,   //每页数量
                        current: params.offset / params.limit + 1,
                    })
                },
                //导入数据之前,设置复选框选中
                responseHandler: function (res) {
                    // bootstrapTableShiroExpire(res);
                    res.rows.forEach(function (row) {
                        row.select = $.inArray(row.id, res.selectedIds) !== -1;
                    })
                    return res;
                },
                sidePagination: "server",//分页方式：client客户端分页，server服务端分页（*）
                pageSize: 10,//每页的记录行数（*）
                pageList: [10, 20, 50],//可供选择的每页的行数（*）
                minimumCountColumns: 2,//最少允许的列数
                clickToSelect: true,//是否启用点击选中行
                uniqueId: "id", //每一行的唯一标识，一般为主键列
                singleSelect: false,//是否单选
                columns: roleColumns,
                //没有匹配的结果
                formatNoMatches: function () {
                    return "111";
                },
                //导入错误
                onLoadError: function (data) {
                    $('#roleTable').bootstrapTable('removeAll');
                }
            });

            $('#roleModal').modal("show");
        }
    }

    //分配角色提交方法
    function saveRoleData() {
        $.ajax({
            type: "post",
            url: requestPath.relateRole,
            data: {
                roleIds: getSelectedIds($("#roleTable")).join(','),
                userId: $("#ruid").val()
            },
            dataType: "json",
            success: function (data) {
                let success = data.success,
                    message = data.message
                swal(message)
                if (success) {
                    setTimeout(function () {
                        window.location.href = requestPath.index;
                    }, 1000);
                }
            }
        })
    }

    //选择所属机构
    function relateOrg() {
        //判断是否有选中的数据
        if (validCheckOne()) {
            $('#orgModal').modal("show");
            //初始化树
            initTree();
        }
    }

    //初始化树结构
    function initTree() {
        let setting = {
            check: {
                enable: true,
                chkStyle: "radio",
                radioType: "all"
            },
            view: {
                dblClickExpand: false,
                showLine: true,
                selectedMulti: false
            },
            data: {
                simpleData: {
                    enable: true,
                    idKey: "id",
                    pIdKey: "parentId",
                    rootPId: ""
                }
            }
        };

        $.ajax({
            type: "post",
            url: requestPath.relateOrgIndex,
            data: {
                userId: getSelectedId()
            },
            dataType: "json",
            success: function (data) {
                $.fn.zTree.init($("#tree"), setting, data);
            }
        });
    }

    function saveTree() {
        let treeObj = $.fn.zTree.getZTreeObj("tree");
        let nodes = treeObj.getCheckedNodes(true);
        $.ajax({
            type: "post",
            url: requestPath.relateOrg,
            data: {
                orgId: nodes[0].id,
                userId: getSelectedId()
            },
            dataType: "json",
            success: function (data) {
                swal(data.message)
                if (data.success) {
                    setTimeout(function () {
                        window.location.href = requestPath.index
                    }, 1000);
                }
            }
        })
    }

    function delById(url, id) {
        url = url || requestPath.del
        id = id || $("#id").val()
        swal({
                title: "您确定要删除吗?",
                text: "删除后将无法恢复,请谨慎操作!",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "删除",
                closeOnConfirm: false
            }, function () {
                $.ajax({
                    type: "get",
                    url: requestPath.validDel,
                    data: "id=" + id,
                    dataType: "json",
                    success: function (data) {
                        let success = data.success,
                            message = data.message
                        if (success) {
                            deleteUser(id)
                        } else {
                            swal({
                                title: message,
                                type: "warning",
                                showCancelButton: true,
                                confirmButtonColor: "#DD6B55",
                                confirmButtonText: "删除",
                                closeOnConfirm: false
                            }, function () {
                                deleteUser(id)
                            })
                        }
                    }
                })
            }
        )
    }

    function deleteUser(id) {
        $.ajax({
            type: "get",
            url: requestPath.del,
            data: "id=" + id,
            dataType: "json",
            success: function (data) {
                let success = data.success,
                    message = data.message
                swal(message)
                if (success) {
                    setTimeout(function () {
                        location.href = requestPath.index
                    }, 1000);
                }
            }
        })
    }
    function unlock() {
      if (validCheckOne($('#dataTable'))) {
        $.ajax({
          type: "get",
          url: requestPath.unlock,
          data: "id=" + getSelectedId(),
          dataType: "json",
          success: function (data) {
            let success = data.success,
                    message = data.message
            swal(message)
            if (success) {
              setTimeout(function () {
                location.href = requestPath.index
              }, 1000);
            }
          }
        })
      }

    }
</script>
</html>
